import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { GetToken, GetLeave } from "../utils/token";
import { RouterList, RouteList } from "./arr";
import pinia from "../stores/index";
import main from "../stores/main";
const mians = main(pinia);
// console.log();
const route = createRouter({
  history: createWebHistory(),
  routes: RouterList.concat(),
});

route.beforeEach((to, from, next) => {
  if (to.name) {
    if (GetToken() != null && to.name != "error") {
      let Leave = GetLeave();
      if (to.name === "login") {
        next({ name: "/" });
      }
      if (Number(Leave) === 1) {
        if (route.options.routes.indexOf(RouteList[0]) == -1) {
          let one: Array<RouteRecordRaw> = [];
          one = RouterList.concat();
          for (let index = 0; index < RouteList.length; index++) {
            route.addRoute(RouteList[index]);
            one.push(RouteList[index]);
          }
          route.options.routes = one;
          next({ ...to });
          // next();
        } else {
          next();
        }
      } else {
        for (let index = 0; index < RouteList.length; index++) {
          route.addRoute(RouterList[index]);
        }
        route.options.routes = RouterList;

        next();
      }
    } else {
      if (to.name != "login") {
        next({ name: "login" });
      } else {
        next();
      }
      // next();
    }
  } else {
    let Leave = GetLeave();
    if (Number(Leave) === 1) {
      if (route.options.routes.indexOf(RouteList[0]) == -1) {
        let one: Array<RouteRecordRaw> = [];
        one = RouterList.concat();
        for (let index = 0; index < RouteList.length; index++) {
          route.addRoute(RouteList[index]);
          one.push(RouteList[index]);
        }
        route.options.routes = one;

        next({ ...to });
        // next();
      } else {
        next({ name: "error" });
      }
    } else {
      for (let index = 0; index < RouteList.length; index++) {
        route.addRoute(RouterList[index]);
      }
      route.options.routes = RouterList;

      next();
    }

    //
  }

  mians.selectedKey[0] = to.path.split("/")[to.path.split("/").length - 1];
  // console.log(to.path.split("/")[to.path.split("/").length - 1]);

  mians.openKey[0] = "/" + to.path.split("/")[1];
  if (to.name === "/") {
    mians.selectedKey[0] = "/";
    mians.openKey[0] = "/Home";
  }

  // if (to.name != "login" && GetToken() == null && to.name != "error") {
  //   next({ name: "login" });
  // } else if (to.name != "login" && GetToken() !== null) {
  //   // next({ path: "/" });
  //   if (Number(Leave) === 1) {
  //     for (let index = 0; index < RouteList.length; index++) {
  //       route.addRoute(RouteList[index]);
  //     }
  //     next({ ...to });
  //   } else {
  //     next();
  //   }
  // } else {
  //   next();
  // }
});

export default route;
